package com.mgface.tech;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project netty_fly
 * @create 2020-06-18 20:05
 **/
public class EchoClient {
    private final String host;
    private int port;
    public EchoClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup g =new  NioEventLoopGroup();
        try{
            Bootstrap boot = new Bootstrap();
            boot.group(g)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture sync = boot.connect().sync();
            sync.channel().closeFuture().sync();
        }finally {
            g.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        EchoClient localhost = new EchoClient("localhost", 8888);
        localhost.start();
    }
}
